import React, { Component } from 'react';
import { Link, routerRedux } from 'dva/router';
import { connect } from 'dva';
import { List, InputItem,NavBar, Checkbox, Toast, Flex,Icon,WingBlank,Button,Radio, Modal, Grid} from 'antd-mobile';
import NavTopBar from '../../components/NavTopBar/NavTopBar';
import Img from "../../components/Img/Img";
import select2 from '../../assets/img/select2.svg';
import select1 from '../../assets/img/select1.svg';
import { createForm } from 'rc-form';
import {payMent} from  "./payMent.less";
import { list_box, p_left, list_height, span_available, span_used, span_remaining, modal_input, div_flex, bottom_box, grid_box, img_width, radio_box, img_height_problem, opacity_0 } from './payMent.less'

const {Item} =List;
const RadioItem = Radio.RadioItem;
const CheckboxItem = Checkbox.CheckboxItem;


function floatSub(arg1,arg2){
    var r1,r2,m,n;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2));
    //动态控制精度长度
    n=(r1>=r2)?r1:r2;
    return ((arg1*m-arg2*m)/m).toFixed(n);
};

class PayMent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            paymentEntities: [],
            value: "YE",
            YE: false,
            YEModal: false,
            YEpassword: "",
            isRecharge: true,
        };
        this.elInput = null;
    }

    obtainFocus = () => {
        // this.elInput ? this.elInput.focus() : setTimeout(() => this.obtainFocus(), 10)
        console.warn('obtainFocus,,,,,,,,,,,,,,获取光标。。。。。。');
        if (this.elInput) this.elInput.focus()
        else setTimeout(() => this.obtainFocus(), 10)
    };

    componentWillMount(){
        this.props.dispatch({type:"orderList/PayListEFF"})
    }

    componentDidUpdate() {
        if (this.state.YEModal && this.elInput) this.elInput.focus();
    }


    componentDidMount() {
        const isRecharge = this.props.match.params.data.split(",")[3];

        if (isRecharge) this.setState({isRecharge: false, value: "weiscan"})

    }



    confirmPayment = e => {

       //  this.props.dispatch(routerRedux.push({
       //     pathname:`/showCode?code=081UWvkO1etcF11aKsjO1m9ukO1UWvk0&state=123`
       // }))

       const orderId = this.props.match.params.orderId;
       console.warn(orderId, '从订单列表过来的有orderId.....................................');

       // 余额支付。。。
        if (this.state.value == "YE") {
            this.setState({YEModal: true});
            return this.obtainFocus();
        };

        if (this.state.value == "weiscan") {
            // 微信支付。。。
            var APPID = "wx2a29d7c7b3575fc6";
            var redirect_uri = `http://bbch5.leimingtech.com/showCode`;
            console.warn( decodeURIComponent("11%2C%2CP20180602100901884") );
            var isOrderId;
            if (orderId) isOrderId = `,${orderId}`;

            // var url = `https://open.weixin.qq.com/connect/qrconnect?appid=${APPID}&redirect_uri=${ encodeURI(redirect_uri) }&response_type=code&scope=snsapi_login&state=123#wechat_redirect`

            // var url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${encodeURIComponent(redirect_uri)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirec`;
            // document.location.href = url;

            // document.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID + '&redirect_uri=' + encodeURIComponent(redirect_uri + this.props.match.params.data.split(",")[2] + '/' + this.props.match.params.data.split(",")[0]) + '&response_type=code&scope=snsapi_base&state=123#wechat_redirect';


            return document.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${ APPID }&redirect_uri=${ encodeURIComponent(redirect_uri) }&response_type=code&scope=snsapi_userinfo&state=${ this.props.match.params.data }${isOrderId}#wechat_redirect`;

            // console.warn(this.props.match.query.code, "微信中code");
            //
            // this.props.dispatch({type: "orderList/WeiXinPayment", obj: {code: this.props.match.query.code, ordercode: this.props.match.params.data.split(",")[2]}}).then(res => {
            //     console.log(res, "密码验证。。。");
            // })

        }
        // this.props.dispatch(routerRedux.push({
        //     pathname:`/paySuccess/${this.props.match.params.data}`
        // }))

        if (this.state.value == "ZFB") {
            // this.props.dispatch({type: "orderList/ZFBpayment", obj: {orderCode: this.props.match.params.data.split(",")[2]}}).then(res => {
            //     console.log(res, "支付宝回调。。。。");
            //     // document.location.href = `https://openapi.alipay.com/gateway.do${ "?" + res.ret.data}`;
            // });

            var isOrderId;
            if (orderId) isOrderId = `&orderId=${orderId}`;

            return document.location.href =`http://bbch5.leimingtech.com/api/rest/api/v6.0/ali?orderCode=${ this.props.match.params.data.split(",")[2] }&backUrl=/paySuccess/${this.props.match.params.data}&failUrl=/payMent/${this.props.match.params.data}${isOrderId}`;

        }

    }
    spanClick = () => {
         this.elInput.focus();
        // return (
        //     <span onClick={() => this.elInput.focus()}>{ `${YEpassword}`[n] }</span>
        // )
    }
    YESubmit = () => {
        const orderId = this.props.match.params.orderId;
        console.warn(orderId, '从订单列表过来的有orderId.....................................');

        this.props.dispatch({type: "orderList/YEverification", obj: {paypassword: this.props.form.getFieldsValue().YEpassword, ordercode: this.props.match.params.data.split(",")[2], orderId}}).then(res => {
            console.log(res, "数据。。。");
            if (res.code == 200) this.props.dispatch(routerRedux.replace({pathname: `/paySuccess/${this.props.match.params.data}`}));
            else {
                Toast.fail(res.msg);
                console.log(this.props.form, this.props.form.setFieldsValue);
                this.props.form.setFieldsValue({YEpassword: ""});
            };
        })
    }

    componentDidUpdate() {
        const { YEpassword = "" } = this.props.form.getFieldsValue();
        console.warn(YEpassword, YEpassword.length == 6, 'YEpassword   componentDidUpdate');
        if (YEpassword.length == 6) this.YESubmit();
    }

    render() {
        const {paymentEntities=[]}=this.props.orderList;
        const payAmount = this.props.match.params.data.split(",")[0];
        const { YE } = this.state;
        const { YEpassword = "" } = this.props.form.getFieldsValue();
        const { getFieldProps } = this.props.form;





        console.log(this.props.form, "render   ++");
        // console.log(this.props.form.getFieldsValue(), "getFieldsValue");


        return (
            <Flex style={{
                backgroundColor: "#F7F7F7",
                height:"100%",
                width:"100%"
            }} direction="column"
                  className={payMent}
            >
                <NavBar
                    style={{ width:"100%", backgroundColor:"#fff", color:'#000' }}
                    mode="dark"
                    icon={<Icon type="left" style={{width:".7rem",height:".7rem"}} />}
                    onLeftClick={() => {
                        if(this.state.isRecharge){
                            this.props.dispatch(routerRedux.replace({
                                pathname: `/orderList/${1}`,
                            }));
                        }else{ this.props.dispatch(routerRedux.replace({
                            pathname: `/my`,
                        }));}

                    }}
                    rightContent={[
                        <div
                            onClick={() => {
                                this.props.dispatch(routerRedux.replace({
                                    pathname: `/orderList/${0}`,
                                }));
                            }}
                            style={{ padding: '0.15rem 0.2rem', color:"#999" }}
                            key="1"
                        >订单中心
                        </div>
                    ]}
                >
                    名食汇收银台
                </NavBar>
                {/*
                <List style={{width:"100%", backgroundColor: "#F7F7F7"}}>
                    <Item style={{margin: ".2rem 0rem", height: "1rem"}} extra={<span style={{color:"#ff0036"}}>{this.props.match.params.data.split(",")[0]}元</span>}>订单金额</Item>
                    {
                        paymentEntities.map((value,i)=>{
                            return <RadioItem key={i} checked={this.state.value === i} onChange={()=>{this.setState({value:i})}}
                            >
                                <Img src={value.logo}/>
                                {value.name}
                                </RadioItem>
                        })
                    }
                </List>
                */}


                <List className={ list_box }>
                    <Item className={ list_height } style={{margin: ".3rem 0rem 0rem"}} extra={<span style={{color:"#ff0036"}}>{ payAmount }元</span>}>订单金额</Item>
                </List>

                <p className={ p_left }>第三方支付</p>

                <List className={ list_box }>
                    {
                        paymentEntities.filter(e => e.code != "YE").map((value,i)=>{
                            return <RadioItem style={{height: ".88rem", fontSize: ".28rem"}} key={i} checked={this.state.value === value.code} onChange={() => this.setState({value: value.code})}
                            >
                                {
                                    value.code != "ZFB" ? <Img src={value.logo}/> : <Img className={ img_height_problem } src={value.logo}/>
                                }
                                 {value.name}
                                {this.state.value === value && false ? <span className={ span_used }>￥{ payAmount }</span> : ""}
                                </RadioItem>
                        })
                    }
                    {/* <RadioItem style={{height: ".88rem", fontSize: ".28rem"}} key={i} checked={this.state.value === value.code} onChange={()=>{this.setState({value: "wx"})}}>
                        <Img src={value.logo}/>
                        {value.name}
                        {this.state.value === value && false ? <span className={ span_used }>￥{ payAmount }</span> : ""}
                        </RadioItem> */}

                        {/* <div className={ radio_box }>
                            <img src={require("../../assets/img/wxPayment.png")} />
                            微信支付
                            {
                                this.state.value == "wx" ? <span></span> : ""
                            }

                            <span><Icon type={select1.id} /></span>
                        </div>

                        <div className={ radio_box }>
                            <img src={require("../../assets/img/ZFBpayment.png")} />
                            支付宝支付
                            <span><Icon type={select1.id} /></span>
                        </div> */}
                </List>

                {
                    this.state.isRecharge ? <p className={ p_left }>我的钱包</p> : ""
                }

                {   this.state.isRecharge ?
                    <List className={ list_box }>
                        {
                            paymentEntities.filter(e => e.code == "YE").map((value,i)=>{
                                if (value.balance < payAmount && this.state.value == "YE") this.setState({value: "weiscan"})
                                return <RadioItem style={{height: ".88rem"}} key={i} checked={this.state.value === "YE"} onChange={() => value.balance >= payAmount && this.setState({value: "YE"})}
                                >
                                    <Img className={ img_width } style={{marginRight: ".24rem"}} src={value.logo}/>
                                    {value.name}
                                    {this.state.value === "YE" ?
                                        <span className={ span_used }>已用￥{ (value.balance >= payAmount ? payAmount : value.balance) || '0.00' }</span>:
                                        <span className={ span_available }>可用￥{ value.balance }</span>
                                    }
                                    {this.state.value === "YE" && value.balance >= payAmount ? <span className={ span_remaining }>剩余￥{ floatSub(value.balance, payAmount) }</span> : "" }
                                    </RadioItem>
                            })
                        }
                        {/* <div className={ radio_box }>
                            <img src={require("../../assets/img/YEpayment.png")} />
                            余额支付
                            <span><Icon type={select1.id} /></span>
                        </div> */}
                    </List> : ""
                }


                <Button style={{color:"#fff",backgroundColor:"#ff0036",position:"fixed",bottom:"0",width:"100%"}} onClick={ this.confirmPayment }>确认支付</Button>


                <Modal
                    className={ modal_input }
                    visible={ this.state.YEModal }
                    closable={true}
                    transparent
                    maskClosable={true}
                    onClose={ () => {
                        this.setState({YEModal: false});
                        this.props.form.setFieldsValue({YEpassword: ""});
                    }}
                    title="请输入密码支付"
                    // footer={[{ text: '取消', onPress: () => { this.setState({YEModal: false}) } },
                        // { text: '确认提交', onPress: this.YESubmit }]}
                    wrapProps={{ onTouchStart: this.onWrapTouchStart }}
                    >

                    <div className={ grid_box }>
                        <span onClick={ this.spanClick }>{ `${YEpassword}`[0] && "*" }</span>
                        <span onClick={ this.spanClick }>{ `${YEpassword}`[1] && "*" }</span>
                        <span onClick={ this.spanClick }>{ `${YEpassword}`[2] && "*" }</span>
                        <span onClick={ this.spanClick }>{ `${YEpassword}`[3] && "*" }</span>
                        <span onClick={ this.spanClick }>{ `${YEpassword}`[4] && "*" }</span>
                        <span onClick={ this.spanClick }>{ `${YEpassword}`[5] && "*" }</span>
                    </div>
                    <InputItem
                        className={ opacity_0 }
                        {...getFieldProps('YEpassword')}
                        ref={el => this.elInput = el}
                        type="number"
                        maxLength="6"
                        >
                    </InputItem>


                </Modal>
            </Flex>
        );
    }
}

export default connect(({ orderList }) => ({ orderList }))(createForm()(PayMent));
